<template>
  <div>
    <Card dis-hover>
      <Row style="margin-bottom: 10px;">
        <Col span="24" style="text-align: right;">
          <Button @click="prevStep" type="success" style="margin-right: 10px;" :disabled="current===0">
            <Icon type="ios-arrow-back"></Icon>
            上一步
          </Button>
          <Button @click="nextStep(current)" type="success" style="margin-right: 10px;" :disabled="current===2">下一步
            <Icon type="ios-arrow-forward"></Icon>
          </Button>
          <Button @click="save" icon="md-time" type="primary" :disabled="current!==2">保存</Button>
        </Col>
      </Row>
      <Steps :current="current" style="margin-top:20px;margin-bottom:20px;">
        <Step title="基本信息"></Step>
        <Step title="选择表单"></Step>
        <Step title="设计流程"></Step>
      </Steps>

      <Card dis-hover v-show="current===0" style="height: calc(100vh - 272px);">
        <Form ref="schemeForm0" :model="flowScheme" label-position="top" :rules="schemeRule0">
          <FormItem label="流程模板名称" prop="schemeName">
            <Input v-model="flowScheme.schemeName" clearable maxlength="512" placeholder=""></Input>
          </FormItem>
          <FormItem label="流程模板描述" prop="description">
            <Input v-model="flowScheme.description" type="textarea" :rows="4" clearable placeholder=""></Input>
          </FormItem>
        </Form>
      </Card>
      <Card dis-hover v-show="current===1" style="height: calc(100vh - 272px);">
        <Form ref="schemeForm1" :model="flowScheme" label-position="top" :rules="schemeRule1">
          <FormItem label="表单模板" prop="formName">
            <Input ref="formName" v-model="flowScheme.formName" readonly clearable placeholder=""
                   @on-focus="schemeFocus" @on-clear="schemeClear"></Input>
          </FormItem>
        </Form>
        <Divider/>
        <form-build ref="form0" :form-template="JSON.parse(formScheme.schemeContent)" :models="{}" :disabled="true"
                    :render-preview="false"
                    v-if="formScheme.formType===0 && formScheme.schemeContent!==''"></form-build>
        <component ref="form1" :is="formScheme.schemeContent" :disabled="true" :data="{}"
                   v-if="formScheme.schemeContent!=='' && formScheme.formType===1"></component>
      </Card>
      <flow-area v-if="current===2" ref="flow" :fields="fields"></flow-area>

    </Card>
    <form-scheme-select-modal v-if="formSchemeSelectModalMount" v-model="formSchemeSelectModalShow"
                              :modal-data="formSchemeSelectModalData"
                              @on-submit="obtainSchemes"></form-scheme-select-modal>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import Util from '@/lib/util';
import FlowScheme from '@/store/entities/flow/flow-scheme/flow-scheme';
import FlowArea from '@/components/flow/flow-area.vue';
import FormSchemeSelectModal from '@/components/common-modal/form-scheme-select-modal.vue';
import FormScheme from '@/store/entities/form/form-scheme/form-scheme';
import {formParser} from '@/lib/form-parser';

@Component({
  components: {FormSchemeSelectModal, FlowArea},
})
export default class FlowSchemeInsert extends AbpBase {
  name: string = 'FlowSchemeInsert';
  current: number = 0;
  fields: any[] = [];


  formSchemeSelectModalMount: boolean = false;
  formSchemeSelectModalShow: boolean = false;
  formSchemeSelectModalData: any = {};
  selectedSchemes: any[] = [];
  flowScheme: FlowScheme = new FlowScheme();
  formScheme: FormScheme = new FormScheme();
  schemeRule0 = {
    schemeName: [
      {
        required: true,
        message: '流程模板名称是必须的',
        trigger: 'blur,change',
      },
    ],
  };
  schemeRule1 = {
    formName: [
      {
        validator: (rule, value, callback) => {
          if (!(this.$refs.formName as any).value) {
            callback(new Error('表单模板是必须的'));
          } else {
            callback();
          }

        },
        trigger: 'blur,change',
        required: true,
      },
    ],
  };

  schemeClear() {
    this.selectedSchemes = [];
    this.formScheme.schemeContent='';
  }

  prevStep() {
    this.current--;
  }

  nextStep(step: number) {
    if (step === 0) {
      (this.$refs.schemeForm0 as any).validate(async (valid: boolean) => {
        if (valid) {
          this.current++;
        }
      });
    }
    if (step === 1) {
      (this.$refs.schemeForm1 as any).validate(async (valid: boolean) => {
        if (valid) {
          this.current++;
        }
      });
    }
  }

  async save() {
    if ((this.$refs.flow as any).validateFlow()) {
      this.flowScheme.schemeContent = JSON.stringify((this.$refs.flow as any).getData());
      await this.$store.dispatch({
        type: 'flowScheme/createOrUpdateFlowScheme',
        data: {
          flowScheme: this.flowScheme,
        }
      });
      Util.closePage(this, 'flow-scheme-insert');
      this.$router.push({name: 'flow-scheme'});

      this.$Message.success({
        background: true,
        content: '流程模板 ' + this.flowScheme.schemeName + ' 新建成功',
      });
    }

  }

  schemeFocus() {
    this.formSchemeSelectModalData = {selectedSchemes: this.selectedSchemes};
    this.formSchemeSelectModalMount = true;
    this.$nextTick(() => {
      this.formSchemeSelectModalShow = true;
    });
  }

  obtainSchemes(selectedSchemes) {
    this.selectedSchemes = selectedSchemes;
    this.flowScheme.formName = selectedSchemes[0].schemeName;
    this.flowScheme.formId = selectedSchemes[0].id;
    this.formScheme = selectedSchemes[0];
    this.$nextTick(() => {
      if (this.formScheme.formType === 0) {
        (this.$refs.form0 as any).getData().then(data => {
          this.fields = formParser(JSON.parse(this.formScheme.schemeContent), data);
        });
      }
      if (this.formScheme.formType === 1) {
        this.fields = (this.$refs.form1 as any).getFields();
      }
    });
  }


  beforeDestroy() {
    if (this.$refs.flow) {
      this.$store.commit('flowData/changeName', {
        name: Util.guid(),
      });

      (this.$refs.flow as any).reDraw();
    }
  }
}
</script>

<style lang="less" scoped>

</style>
